import { NodeProps } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import { CaretRightOutlined } from '@ant-design/icons'
import { Collapse, Select, theme } from 'antd'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import { getHttpRequestDefaultParams } from './default'
import OutputCont from './components/OutputCont'
import KeyValueEditor from './components/KeyValueCont'
import BodyEditor from './components/RequestBody'
import RunDrawer from '../components/RunDrawer'
import { useSourceOptions } from '@/pages/workflow/hooks/use-source-options'
import TimeoutEditor from './components/RequestTimeout'
import RequestEditor from './components/RequestAPI'
import { Tabs } from 'antd'
import RetryEditor from './components/RequestRetry'

const HttpRequestPanel: FC<NodeProps> = ({ id, data }: any) => {
  const { flowVariables, setFlowVariables } = useWorkFlowStore()
  const { token } = theme.useToken()
  const [info, setInfo] = useState({ ...getHttpRequestDefaultParams() })
  const editData = (e: any) => {
    const obj = { ...info, ...e }
    setInfo(obj)
    setFlowVariables(id, data.title, obj)
  }

  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      const obj = {
        ...info,
        ...flowVariables[data.id]
      }
      setInfo(obj)
    }
  }, [flowVariables])

  const createCollapseItem = (key: string, label: JSX.Element, children: JSX.Element) => ({
    key,
    label,
    children,
    style: {
      marginBottom: 5,
      background: token.colorFillAlter,
      borderRadius: token.borderRadiusLG,
      border: 'none'
    }
  })

  const requestItems = [
    createCollapseItem(
      '1',
      <CollapseNodeComponent title="API" />,
      <RequestEditor
        value={info}
        onChange={value => editData(value)}
      />
    )
  ]

  const outputItems = [
    createCollapseItem(
      '6',
      <CollapseNodeComponent title="输出" />,
      <OutputCont info={info} editData={editData} />
    )
  ]

  const timeoutItems = [
    createCollapseItem(
      '7',
      <CollapseNodeComponent title="超时设置" />,
      <TimeoutEditor
        value={info}
        onChange={value => editData(value)}
      />
    )
  ]

  const requestParamsItems = [
    createCollapseItem(
      '2',
      <CollapseNodeComponent title="请求参数" />,
      <Tabs
        defaultActiveKey="headers"
        items={[
          {
            key: 'headers',
            label: '请求头',
            children: (
              <KeyValueEditor
                value={info.headers}
                onChange={headers => editData({ headers })}
                info={info}
              />
            )
          },
          {
            key: 'params',
            label: '查询参数',
            children: (
              <KeyValueEditor
                value={info.params}
                onChange={params => editData({ params })}
                info={info}
              />
            )
          },
          {
            key: 'body',
            label: '请求体',
            children: (
              <BodyEditor
                value={info.body}
                onChange={body => editData({ body })}
                sourceOptions={{
                  id: data.id,
                  nodeType: data.type,
                  type: info.body?.type
                }}
              />
            )
          }
        ]}
      />
    )
  ]

  const retryItems = (
    <RetryEditor
      value={info}
      onChange={value => editData(value)}
    />
  )

  const collapseItems = [
    { key: '1', items: requestItems },
    { key: '2', items: requestParamsItems },
    { key: '5', items: timeoutItems },
    { key: '6', items: outputItems },
  ]

  const collapseProps = {
    bordered: false,
    expandIcon: ({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />,
    style: { background: token.colorBgContainer }
  }

  const renderCollapse = (item: any) => (
    <div className="mt-1" key={item.key}>
      <Collapse {...collapseProps} defaultActiveKey={[item.key]} items={item.items} />
    </div>
  )

  const [runDrawerHid, setrunDrawerHid] = useState(false)
  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      /* 单节点运行弹窗 */
      if (flowVariables[data.id].runDrwaerHid === 1) {
        setrunDrawerHid(true)
      }
    }
  }, [flowVariables])

  return (
    <div className="workflow-common-panel flexCol caseOverFlowY">
      <span className="lim_title">发送HTTP请求并处理响应结果</span>
      {collapseItems.map(renderCollapse)}
      {retryItems}
      {runDrawerHid && <RunDrawer nodeData={info} openDef={runDrawerHid} setrunDrawerHid={setrunDrawerHid}></RunDrawer>}
    </div>
  )
}

export default React.memo(HttpRequestPanel)